"""
市场数据相关的Pydantic模型定义
"""

from datetime import datetime
from typing import List, Optional, Dict, Any
from pydantic import BaseModel, Field


class StockPrice(BaseModel):
    """股票价格数据模型"""
    date: datetime = Field(..., description="日期")
    symbol: str = Field(..., description="股票代码")
    open: float = Field(..., description="开盘价")
    high: float = Field(..., description="最高价")
    low: float = Field(..., description="最低价")
    close: float = Field(..., description="收盘价")
    volume: int = Field(..., description="成交量")
    amount: Optional[float] = Field(None, description="成交额")
    pct_change: Optional[float] = Field(None, description="涨跌幅")
    change_amount: Optional[float] = Field(None, description="涨跌额")
    amplitude: Optional[float] = Field(None, description="振幅")
    turnover: Optional[float] = Field(None, description="换手率")


class FinancialMetrics(BaseModel):
    """财务指标数据模型"""
    # 市场数据
    market_cap: Optional[float] = Field(None, description="总市值")
    float_market_cap: Optional[float] = Field(None, description="流通市值")

    # 盈利数据
    revenue: Optional[float] = Field(None, description="营业总收入")
    net_income: Optional[float] = Field(None, description="净利润")
    return_on_equity: Optional[float] = Field(None, description="净资产收益率")
    net_margin: Optional[float] = Field(None, description="销售净利率")
    operating_margin: Optional[float] = Field(None, description="营业利润率")

    # 增长指标
    revenue_growth: Optional[float] = Field(None, description="主营业务收入增长率")
    earnings_growth: Optional[float] = Field(None, description="净利润增长率")
    book_value_growth: Optional[float] = Field(None, description="净资产增长率")

    # 财务健康指标
    current_ratio: Optional[float] = Field(None, description="流动比率")
    debt_to_equity: Optional[float] = Field(None, description="资产负债率")
    free_cash_flow_per_share: Optional[float] = Field(None, description="每股经营性现金流")
    earnings_per_share: Optional[float] = Field(None, description="每股收益")

    # 估值比率
    pe_ratio: Optional[float] = Field(None, description="市盈率（动态）")
    price_to_book: Optional[float] = Field(None, description="市净率")
    price_to_sales: Optional[float] = Field(None, description="市销率")

    # === 新增：财务报表数据（最新期） ===
    # 当期财务报表数据
    operating_revenue: Optional[float] = Field(None, description="营业总收入（当期）")
    # net_income_current: Optional[float] = Field(None, description="净利润（当期）")
    operating_profit: Optional[float] = Field(None, description="营业利润（当期）")
    working_capital: Optional[float] = Field(None, description="营运资金（当期）")
    depreciation_and_amortization: Optional[float] = Field(None, description="折旧和摊销（当期）")
    capital_expenditure: Optional[float] = Field(None, description="资本支出（当期）")
    free_cash_flow: Optional[float] = Field(None, description="自由现金流（当期）")

    # 上期财务报表数据（用于同比分析）
    previous_operating_revenue: Optional[float] = Field(None, description="营业总收入（上期）")
    previous_net_income: Optional[float] = Field(None, description="净利润（上期）")
    previous_operating_profit: Optional[float] = Field(None, description="营业利润（上期）")
    previous_working_capital: Optional[float] = Field(None, description="营运资金（上期）")
    previous_depreciation_and_amortization: Optional[float] = Field(None, description="折旧和摊销（上期）")
    previous_capital_expenditure: Optional[float] = Field(None, description="资本支出（上期）")
    previous_free_cash_flow: Optional[float] = Field(None, description="自由现金流（上期）")


class MarketData(BaseModel):
    """综合市场数据模型（扩展支持东方财富接口的所有字段）"""
    # 基础信息
    symbol: str = Field(..., description="股票代码")
    
    # 价格数据
    current_price: Optional[float] = Field(None, description="最新价")
    open_price: Optional[float] = Field(None, description="今开")
    high_price: Optional[float] = Field(None, description="最高")
    low_price: Optional[float] = Field(None, description="最低")
    prev_close: Optional[float] = Field(None, description="昨收")
    
    # 涨跌数据
    pct_change: Optional[float] = Field(None, description="涨跌幅(%)")
    change_amount: Optional[float] = Field(None, description="涨跌额")
    amplitude: Optional[float] = Field(None, description="振幅(%)")
    speed: Optional[float] = Field(None, description="涨速(%)")
    change_5min: Optional[float] = Field(None, description="5分钟涨跌(%)")
    change_60d: Optional[float] = Field(None, description="60日涨跌幅(%)")
    change_ytd: Optional[float] = Field(None, description="年初至今涨跌幅(%)")
    
    # 成交数据
    volume: Optional[int] = Field(None, description="成交量")
    turnover: Optional[float] = Field(None, description="成交额")
    turnover_rate: Optional[float] = Field(None, description="换手率(%)")
    volume_ratio: Optional[float] = Field(None, description="量比")
    
    # 估值数据
    pe_ratio: Optional[float] = Field(None, description="市盈率-动态")
    pb_ratio: Optional[float] = Field(None, description="市净率")
    market_cap: Optional[float] = Field(None, description="总市值")
    float_market_cap: Optional[float] = Field(None, description="流通市值")
    
    # 保留原有字段以兼容性
    average_volume: Optional[int] = Field(None, description="平均成交量")
    fifty_two_week_high: Optional[float] = Field(None, description="52周最高价")
    fifty_two_week_low: Optional[float] = Field(None, description="52周最低价")
    beta: Optional[float] = Field(None, description="Beta系数")
    dividend_yield: Optional[float] = Field(None, description="股息率")


class NewsItem(BaseModel):
    """新闻数据模型"""
    title: str = Field(..., description="新闻标题")
    content: Optional[str] = Field(None, description="新闻内容")
    publish_time: datetime = Field(..., description="发布时间")
    source: Optional[str] = Field(None, description="新闻来源")
    url: Optional[str] = Field(None, description="新闻链接")
    sentiment_score: Optional[float] = Field(None, description="情感分数")
    importance: Optional[float] = Field(None, description="重要性评分")


class MacroData(BaseModel):
    """宏观经济数据模型"""
    indicator_name: str = Field(..., description="指标名称")
    value: float = Field(..., description="指标值")
    date: datetime = Field(..., description="数据日期")
    unit: Optional[str] = Field(None, description="单位")
    source: Optional[str] = Field(None, description="数据来源")
    description: Optional[str] = Field(None, description="指标描述")


class StockBasicInfo(BaseModel):
    """股票基本信息数据模型"""
    # 基础信息
    symbol: str = Field(..., description="股票代码")
    name: Optional[str] = Field(None, description="股票简称")
    latest_price: Optional[float] = Field(None, description="最新价格")

    # 股本信息
    total_shares: Optional[float] = Field(None, description="总股本")
    float_shares: Optional[float] = Field(None, description="流通股")

    # 市值信息
    total_market_cap: Optional[float] = Field(None, description="总市值")
    float_market_cap: Optional[float] = Field(None, description="流通市值")

    # 行业信息
    industry: Optional[str] = Field(None, description="所属行业")

    # 上市信息
    listing_date: Optional[str] = Field(None, description="上市时间")

    # 数据更新时间
    update_time: Optional[datetime] = Field(default_factory=datetime.now, description="数据更新时间")


class TechnicalIndicators(BaseModel):
    """技术指标数据模型"""
    # 移动平均线SMA
    sma5: Optional[float] = Field(None, description="5日移动平均(SMA)")
    sma10: Optional[float] = Field(None, description="10日移动平均(SMA)")
    sma20: Optional[float] = Field(None, description="20日移动平均(SMA)")
    sma60: Optional[float] = Field(None, description="60日移动平均(SMA)")
    # 移动平均线EMA
    ema8: Optional[float] = Field(None, description="8日移动平均(EMA)")
    ema21: Optional[float] = Field(None, description="21日移动平均(EMA)")
    ema55: Optional[float] = Field(None, description="55日移动平均(EMA)")

    # MACD指标
    macd: Optional[float] = Field(None, description="MACD值")
    signal_line: Optional[float] = Field(None, description="信号线")
    macd_histogram: Optional[float] = Field(None, description="MACD柱状图")

    # RSI指标
    rsi: Optional[float] = Field(None, description="RSI相对强弱指标")

    # 布林带
    bb_upper: Optional[float] = Field(None, description="布林带上轨")
    bb_middle: Optional[float] = Field(None, description="布林带中轨")
    bb_lower: Optional[float] = Field(None, description="布林带下轨")

    # 成交量指标
    volume_ma5: Optional[float] = Field(None, description="5日成交量移动平均")
    volume_ma20: Optional[float] = Field(None, description="20日成交量移动平均")

    # 基础动量指标
    # momentum: Optional[float] = Field(None, description="动量指标")
    # rate_of_change: Optional[float] = Field(None, description="变化率")

    # === 新增 高级技术指标 ===
    # 动量指标
    momentum_1m: Optional[float] = Field(None, description="1个月动量（20个交易日）")
    momentum_3m: Optional[float] = Field(None, description="3个月动量（60个交易日）")
    momentum_6m: Optional[float] = Field(None, description="6个月动量（120个交易日）")
    volume_ratio_5: Optional[float] = Field(None, description="成交量比率（相对于5日平均成交量）")
    volume_ratio_20: Optional[float] = Field(None, description="成交量比率（相对于20日平均成交量）")
    momentum_1w: Optional[float] = Field(None, description="1周动量（5个交易日）")
    
    # 波动率指标
    historical_volatility: Optional[float] = Field(None, description="历史波动率（20日年化）")
    volatility_regime: Optional[float] = Field(None, description="波动率区间（相对于过去120天的位置）")
    volatility_z_score: Optional[float] = Field(None, description="波动率Z分数")
    atr_ratio: Optional[float] = Field(None, description="真实波动幅度比率（ATR/收盘价）")

    # 统计套利指标
    hurst_exponent: Optional[float] = Field(None, description="赫斯特指数（120日滚动计算）")
    skewness: Optional[float] = Field(None, description="偏度（20日滚动计算）")
    kurtosis: Optional[float] = Field(None, description="峰度（20日滚动计算）")


class DataCollectionSummary(BaseModel):
    """数据收集汇总模型"""
    ticker: str = Field(..., description="股票代码")
    start_date: str = Field(..., description="开始日期")
    end_date: str = Field(..., description="结束日期")
    data_collected: Dict[str, bool] = Field(..., description="数据收集状态")
    price_records_count: int = Field(0, description="价格数据记录数")
    news_count: int = Field(0, description="新闻数据数量")
    summary: str = Field(..., description="数据收集摘要")
    price_data: List[StockPrice] = Field(..., description="历史价格数据")
    realtime_data: MarketData = Field(..., description="实时行情数据")
    financial_data: FinancialMetrics = Field(..., description="财务数据")
    news_data: List[NewsItem] = Field(..., description="新闻数据")
    technical_indicators: TechnicalIndicators = Field(..., description="技术指标")
    collection_time: datetime = Field(default_factory=datetime.now, description="收集时间")
